package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.GradePositionRequest;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.SchoolDateTime;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 学生所在班级与课程（分班表） 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-03-20
 */
@Service
public class StudentGradeServiceImpl extends ServiceImpl<StudentGradeMapper, StudentGrade> implements IStudentGradeService {

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    CourseSchedulingAlwaysMapper courseSchedulingAlwaysMapper;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    RecordCourseMapper recordCourseMapper;

    @Autowired
    @Lazy
    IStudentClassTypeService iStudentClassTypeService;

    @Autowired
            @Lazy
    IStudentGradeCrushService iStudentGradeCrushService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;


    final Integer presortResidueCourseCount = 3;//剩余课次大于等于3的算成功

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IDictService iDictService;

    @Autowired
    IGradeAutoSetService iGradeAutoSetService;

    @Autowired
    IStudentGradeContinueService iStudentGradeContinueService;


    @Override
    public List<StudentGrade> getReadingData(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId, Integer lessonType) {
        return studentGradeMapper.getReadingData(yearPart, quarterNum, studentId, subjectsId, lessonType);
    }

    /**
     * 更新最后一条数据
     *
     * @return
     */
    @Override
    public boolean updateIsLast(StudentGrade studentGrade) {
        try {
            QueryWrapper<StudentGrade> studentGradeQueryWrapperNew = new QueryWrapper<>();
            studentGradeQueryWrapperNew.eq("year_part", studentGrade.getYearPart());
            studentGradeQueryWrapperNew.eq("quarter_num", studentGrade.getQuarterNum());
            studentGradeQueryWrapperNew.eq("student_id", studentGrade.getStudentId());
            studentGradeQueryWrapperNew.ne("status", 3);
            studentGradeQueryWrapperNew.eq("subjects_id", studentGrade.getSubjectsId());
            studentGradeQueryWrapperNew.eq("lesson_type", studentGrade.getLessonType());
            studentGradeQueryWrapperNew.orderByDesc("id");
            List<StudentGrade> studentGradeListNew = this.list(studentGradeQueryWrapperNew);
            Integer i = 0;
            for (StudentGrade studentGradeNew : studentGradeListNew) {
                if (i == 0) {
                    studentGradeNew.setIsLast(1);
                } else {
                    studentGradeNew.setIsLast(0);
                }
                this.updateById(studentGradeNew);
                i++;
            }
            studentGradeQueryWrapperNew.clear();
            return true;
        } catch (Exception e) {
        }
        return true;
    }

    @Override
    public void updateIsPresort(Long schoolId, Long studentId, Integer yearPart, Integer quarterNum, Long subjectsId, Integer lessonType) {
        Integer yearPartAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);

        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        LocalDate dateNow = LocalDate.now();

        //为了获取年级信息
        OrderDetail lastOrderDetail = orderDetailMapper.getLastOneForStudent(yearPart, quarterNum, studentId, subjectsId, lessonType);

        Integer gradeSection = CommonUtil.getGradeSection(lastOrderDetail.getYearClassId());
        //CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysMapper.getOneForDate(LocalDate.now(), gradeSection);
        CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysMapper.getOneForNum(yearPart,quarterNum,3, gradeSection);//3次课
        if (courseSchedulingAlways != null) {
            //当前学期
            //在三次课之前
            if (!dateNow.isAfter(courseSchedulingAlways.getEndDate())) {
                nextYearPart = yearPart;
                nextQuarterNum = quarterNum;
            }

            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part", nextYearPart);
            studentGradeQueryWrapper.eq("quarter_num", nextQuarterNum);
            studentGradeQueryWrapper.eq("subjects_id", subjectsId);
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("lesson_type",lessonType);
            studentGradeQueryWrapper.ne("status","3");

            if (!nextQuarterNum.equals(quarterNum)) {
                Integer residueCount = orderDetailMapper.getResidueCourseCount(null, studentId, subjectsId, yearPartAndQuarter, lessonType);
                //下个学期
                if (residueCount < this.presortResidueCourseCount) {
                    studentGradeQueryWrapper.eq("is_presort", 1);
                    List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGrade : studentGradeList) {
                        studentGrade.setIsPresort(4);
                        studentGrade.setRemark("课次小于"+this.presortResidueCourseCount+"，" + "时间：" + LocalDateTime.now().withNano(0));
                        this.updateById(studentGrade);
                        iStudentGradeContinueService.changeFail(studentGrade,4);
                    }
                } else {
                    //还没有添加过续报信息
                    Integer presortCount = studentGradeMapper.getPresortCount(yearPart,quarterNum,subjectsId,studentId,lessonType,"1,2,3");
                    if (presortCount == 0){
                        //studentGradeQueryWrapper.ne("is_presort", 1);
                        studentGradeQueryWrapper.orderByDesc("id");
                        studentGradeQueryWrapper.last("limit 1");
                        List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                        for (StudentGrade studentGrade : studentGradeList) {
                            studentGrade.setIsPresort(1);
                            studentGrade.setRemark("课次大于等于"+this.presortResidueCourseCount+"，" + "时间：" + LocalDateTime.now().withNano(0));
                            studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));//修改添加时间
                            this.updateById(studentGrade);
                            iStudentGradeContinueService.addData(studentGrade,1);
                        }
                    }
                }
            } else if (nextQuarterNum.equals(quarterNum)) {
                //当前学期
                if (courseSchedulingAlways.getNum() <= 3) {
                    Integer allCourseCount = orderDetailMapper.getAllCourseCountForSubjects(null,studentId, subjectsId, yearPartAndQuarter, lessonType);
                    if (allCourseCount>=this.presortResidueCourseCount){
                        //还没有添加过续报信息
                        Integer presortCount = studentGradeMapper.getPresortCount(yearPart,quarterNum,subjectsId,studentId,lessonType,"1,2,3");
                        if (presortCount == 0){
                            studentGradeQueryWrapper.orderByDesc("id");
                            studentGradeQueryWrapper.last("limit 1");
                            List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                            for (StudentGrade studentGrade : studentGradeList) {
                                studentGrade.setIsPresort(1);
                                studentGrade.setRemark("课次大于等于"+this.presortResidueCourseCount+"，" + "时间：" + LocalDateTime.now().withNano(0));
                                studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));//修改添加时间
                                this.updateById(studentGrade);
                                iStudentGradeContinueService.addData(studentGrade,1);
                            }
                        }
                    }
                }
            }
        }
    }


    @Override
    public void updateIsPresortForRecord(Long schoolId, Long studentId, Integer yearPart, Integer quarterNum, Long subjectsId, Integer lessonType){
        Integer yearPartAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);

        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        LocalDate dateNow = LocalDate.now();

        //为了获取年级信息
        OrderDetail lastOrderDetail = orderDetailMapper.getLastOneForStudent(yearPart, quarterNum, studentId, subjectsId, lessonType);

        Integer gradeSection = CommonUtil.getGradeSection(lastOrderDetail.getYearClassId());
        //CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysMapper.getOneForDate(LocalDate.now(), gradeSection);
        CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysMapper.getOneForNum(yearPart,quarterNum,3, gradeSection);//3次课
        if (courseSchedulingAlways != null) {
            //当前学期
            //在三次课之前
            if (!dateNow.isAfter(courseSchedulingAlways.getEndDate())) {
                nextYearPart = yearPart;
                nextQuarterNum = quarterNum;
            }

            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part", nextYearPart);
            studentGradeQueryWrapper.eq("quarter_num", nextQuarterNum);
            studentGradeQueryWrapper.eq("subjects_id", subjectsId);
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("lesson_type",lessonType);
            studentGradeQueryWrapper.ne("status","3");

            //当前学期
            if (courseSchedulingAlways.getNum() <= 3) {
                Integer rCount = 3;//已经扣大于等于3课次的学生
                List<RecordCourse> recordCourseList = recordCourseMapper.getRecordCourseCount(yearPart,quarterNum,studentId,1,rCount);
                //还没有添加过续报信息
                Integer presortCount = studentGradeMapper.getPresortCount(yearPart,quarterNum,subjectsId,studentId,lessonType,"1,2,3");
                QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                recordCourseQueryWrapper.eq("year_part", nextYearPart);
                recordCourseQueryWrapper.eq("quarter", nextQuarterNum);
                recordCourseQueryWrapper.eq("subjects_id", subjectsId);
                recordCourseQueryWrapper.eq("student_id", studentId);
                recordCourseQueryWrapper.eq("lesson_type", 1);
                recordCourseQueryWrapper.eq("is_deduct_house", 1);
                //是否上过课
                Long count = iRecordCourseService.count(recordCourseQueryWrapper);

                if (presortCount == 0 && recordCourseList.size()>0){
                    studentGradeQueryWrapper.orderByDesc("id");
                    studentGradeQueryWrapper.last("limit 1");
                    List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGrade : studentGradeList) {
                        studentGrade.setIsPresort(3);
                        studentGrade.setRemark("课次大于等于"+this.presortResidueCourseCount+"，" + "时间：" + LocalDateTime.now().withNano(0));
                        studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));//修改添加时间
                        this.updateById(studentGrade);
                        iStudentGradeContinueService.changeIsPresort(studentGrade,3);

                    }
                }else if (presortCount == 0 && recordCourseList.size() == 0){
                    studentGradeQueryWrapper.orderByDesc("id");
                    studentGradeQueryWrapper.last("limit 1");
                    List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGrade : studentGradeList) {
                        studentGrade.setIsPresort(1);
                        studentGrade.setRemark("课次大于等于"+this.presortResidueCourseCount+"，" + "时间：" + LocalDateTime.now().withNano(0));
                        studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));//修改添加时间
                        this.updateById(studentGrade);
                        iStudentGradeContinueService.changeIsPresort(studentGrade,1);
                    }
                }else if (presortCount > 0 && recordCourseList.size() >0){
                    studentGradeQueryWrapper.in("is_presort",1,2,3);
                    studentGradeQueryWrapper.last("limit 1");
                    List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGrade : studentGradeList) {
                        studentGrade.setIsPresort(2);
                        studentGrade.setRemark("课次大于等于"+this.presortResidueCourseCount+"，" + "时间：" + LocalDateTime.now().withNano(0));
                        studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));//修改添加时间
                        this.updateById(studentGrade);
                        iStudentGradeContinueService.changeIsPresort(studentGrade,2);
                    }
                }
            }
        }

        Integer rCount = 15;//已经扣大于等于15课次的学生
        List<RecordCourse> recordCourseList = recordCourseMapper.getRecordCourseCount(yearPart,quarterNum,studentId,1,rCount);
        //log.error("recordCourseList:" + recordCourseList.size());
        for (RecordCourse recordCourse : recordCourseList) {
            try {
                //还没有添加过续报信息
                Integer presortCount = studentGradeMapper.getPresortCount(yearPart,quarterNum,recordCourse.getSubjectsId(),recordCourse.getStudentId(),recordCourse.getLessonType(),"1,2,3");
                if (presortCount == 0){
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("year_part", yearPart);
                    studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                    studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                    studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                    studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.orderByDesc("id");
                    studentGradeQueryWrapper.last("limit 1");
                    List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGrade : studentGradeList) {
                        studentGrade.setIsPresort(3);
                        studentGrade.setRemark("已上大于等于15，" + "时间：" + LocalDateTime.now().withNano(0));
                        studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));//修改添加时间
                        this.updateById(studentGrade);
                        iStudentGradeContinueService.changeIsPresort(studentGrade,3);
                    }
                }else {
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("year_part", yearPart);
                    studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                    studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                    studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                    studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.in("is_presort",1,2,3);
                    studentGradeQueryWrapper.orderByDesc("id");
                    studentGradeQueryWrapper.last("limit 1");
                    List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGrade : studentGradeList) {
                        if (studentGrade.getIsPresort().equals(1)) {
                            studentGrade.setIsPresort(2);//预分班续报成功
                            this.updateById(studentGrade);
                            iStudentGradeContinueService.changeIsPresort(studentGrade,2);
                        } else {
                            studentGrade.setIsPresort(3);//没有添加预分班的，续报成功
                            this.updateById(studentGrade);
                            iStudentGradeContinueService.changeIsPresort(studentGrade,3);
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    }


    @Override
    public void updateStudentGradeClassTypeId(StudentClassType studentClassType){
        try {
            Quarter quarterNow = iQuarterService.getNowQuarter();
            if (studentClassType.getClassTypeId()!=null){
                UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                studentGradeUpdateWrapper.eq("year_part",quarterNow.getYearPart());
                studentGradeUpdateWrapper.eq("quarter_num",quarterNow.getNum());
                studentGradeUpdateWrapper.eq("student_id",studentClassType.getStudentId());
                studentGradeUpdateWrapper.eq("lesson_type",1);
                studentGradeUpdateWrapper.eq("subjects_id",studentClassType.getSubjectsId());
                studentGradeUpdateWrapper.set("class_type_id_new",studentClassType.getClassTypeId());
                this.update(studentGradeUpdateWrapper);
            }
        }catch (Exception e){
        }

    }

    @Override
    public Integer updateDeleted(Long id, Integer deleted) {
        return studentGradeMapper.updateDeleted(id, deleted);
    }


    @Override
    public void newStudentSchedule(StudentGrade studentGrade) {
        GradePositionRequest gradePositionRequest = iStudentClassTypeService.getAutoDivideClassTypeOrScore(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSubjectsId(),studentGrade.getStudentId(),studentGrade.getYearClassId());
        Integer getType = null;
        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);

        /**
         * 获取未封班的班级
         */
        if (gradePositionRequest.getIsHasData().equals(1)){
            if (studentGrade.getSchedulingScore() == null){
                studentGrade.setSchedulingScore(gradePositionRequest.getScore());
            }
            //1分数，2班型
            getType = gradePositionRequest.getType();
            List<Grade> gradeList = gradeMapper.getSchedulingGrade(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getSubjectsId(),studentGrade.getYearClassId(),studentGrade.getLessonType(),studentGrade.getClassTypeIdNew(),null,getType);

            Grade gradeAdd = null;
            StudentGrade studentGradeCrush = null;

            for (Grade grade:gradeList){
                if (gradeAdd!=null){
                    continue;
                }

                //未满班
                if (grade.getFullCount() == 0 || (grade.getFullCount()>0 && grade.getFullCount()> grade.getStudentCount())){
                    if (gradeAdd == null){
                        gradeAdd = grade;
                    }
                }else {
                    /**
                     * 设置了顺位数据,并按分数添加
                     */
                    if (gradePositionRequest.getType().equals(1)){
                        if (grade.getPositionNum()>0 && grade.getStartScore().compareTo(BigDecimal.ZERO)>0){
                            //获取班级里已排班的新生
                            /*List<StudentGrade> studentGradeList = studentGradeMapper.getSchedulingNewStudent(grade.getId());
                            if (studentGradeList.size()>0){
                                for (StudentGrade studentGradeInfo:studentGradeList){
                                    if (studentGradeInfo.getSchedulingScore().compareTo(BigDecimal.ZERO)>0){
                                        BigDecimal score = studentGrade.getSchedulingScore();
                                        if (score != null){
                                            List<StudentGrade> studentGradeCrushList = studentGradeMapper.getSchedulingNewStudentForScore(grade.getId(),score);
                                            if (studentGradeCrushList.size()>0){
                                                //this.addNewStudentGrade(studentGrade,grade);
                                                //StudentGrade studentGradeCrush = studentGradeCrushList.get(0);
                                                //studentGradeCrush.setAddType(99);//被挤的学生
                                                //this.newStudentSchedule(studentGradeCrush);
                                                if (gradeAdd == null){
                                                    gradeAdd = grade;
                                                    studentGradeCrush = studentGradeCrushList.get(0);
                                                }
                                            }
                                        }
                                    }
                                }
                            }*/

                            //获取是否有被挤出的学生
                            BigDecimal score = studentGrade.getSchedulingScore();
                            if (score != null){
                                List<StudentGrade> studentGradeCrushList = studentGradeMapper.getSchedulingNewStudentForScore(grade.getId(),score);
                                if (studentGradeCrushList.size()>0){
                                    //this.addNewStudentGrade(studentGrade,grade);
                                    //StudentGrade studentGradeCrush = studentGradeCrushList.get(0);
                                    //studentGradeCrush.setAddType(99);//被挤的学生
                                    //this.newStudentSchedule(studentGradeCrush);
                                    for (StudentGrade studentGradeCrushInfo:studentGradeCrushList){
                                        if (gradeAdd == null){
                                            List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.getSchedulingClash(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getStudentId(),grade.getId(),nowDateTime.toString());
                                            //没有排课冲突
                                            if (courseSchedulingDetailList.size() == 0){
                                                //使用课时为0
                                                Integer useCount = studentGradeMapper.getUseCourseCount(studentGradeCrushInfo.getYearPart(),studentGradeCrushInfo.getQuarterNum(),studentGradeCrushInfo.getSchoolId(),studentGradeCrushInfo.getSubjectsId(),studentGradeCrushInfo.getStudentId(),studentGradeCrushInfo.getLessonType());
                                                if (useCount == 0){
                                                    gradeAdd = grade;
                                                    studentGradeCrush = studentGradeCrushInfo;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (gradeAdd!=null){
                this.addNewStudentGrade(studentGrade,gradeAdd,studentGradeCrush,gradePositionRequest.getType());
            }
        }
    }

    public void addNewStudentGrade(StudentGrade studentGrade,Grade grade,StudentGrade studentGradeCrush,Integer positionType){
        if (studentGrade.getAddType()!=null && studentGrade.getAddType().equals(99)){
            StudentGradeCrush studentGradeCrushAdd = new StudentGradeCrush();
            studentGradeCrushAdd.setYearPart(studentGrade.getYearPart());
            studentGradeCrushAdd.setQuarterNum(studentGrade.getQuarterNum());
            studentGradeCrushAdd.setSubjectsId(studentGrade.getSubjectsId());
            studentGradeCrushAdd.setOutGradeId(studentGrade.getGradeId());
            studentGradeCrushAdd.setIntGradeId(grade.getId());
            studentGradeCrushAdd.setStudentId(studentGrade.getStudentId());
            iStudentGradeCrushService.save(studentGradeCrushAdd);

            UpdateWrapper<StudentGrade> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("year_part",studentGrade.getYearPart());
            updateWrapper.eq("quarter_num",studentGrade.getQuarterNum());
            updateWrapper.eq("student_id",studentGrade.getStudentId());
            updateWrapper.eq("subjects_id",studentGrade.getSubjectsId());
            updateWrapper.eq("lesson_type",studentGrade.getLessonType());
            updateWrapper.eq("reading_status",1);
            updateWrapper.set("reading_status",2);
            studentGradeMapper.update(null,updateWrapper);

            studentGrade.setGradeId(grade.getId());
            studentGrade.setAddType(2);
            studentGrade.setIsLast(1);
            studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
            studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));
            this.updateById(studentGrade);
        }else {
            StudentGrade studentGradeAdd = new StudentGrade();
            BeanUtils.copyProperties(studentGrade,studentGradeAdd);
            studentGradeAdd.setId(null);
            studentGradeAdd.setAddType(2);
            studentGradeAdd.setIsLast(1);
            studentGradeAdd.setUseCourseCount(0);
            studentGradeAdd.setRemark("");
            studentGradeAdd.setGradeId(grade.getId());
            this.save(studentGradeAdd);
        }

        if (studentGradeCrush!=null){
            studentGradeCrush.setAddType(99);//被挤的学生
            this.newStudentSchedule(studentGradeCrush);
        }

        /**
         * 封班
         */
        if (positionType.equals(1)){
            List<Grade> gradeList = gradeMapper.getSchedulingGrade(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getSubjectsId(),studentGrade.getYearClassId(),studentGrade.getLessonType(),studentGrade.getClassTypeIdNew(),grade.getId(),positionType);
            if (gradeList.size()>0){
                Grade gradeInfo = gradeList.get(0);
                if (gradeInfo.getFullCount().equals(gradeInfo.getStudentCount())){
                    //没有低于最低分的学生
                    List<StudentGrade> studentGradeCrushList = studentGradeMapper.getSchedulingNewStudentForScore(grade.getId(),grade.getStartScore());
                    if (studentGradeCrushList.size() == 0){
                        grade.setIsSeal(1);
                        gradeMapper.updateById(grade);//修改为封班
                    }
                }
            }
        }

        //更新为最后一条
        //this.updateIsLast(yearPart, quarterNum, studentId, subjectsId, lessonType);
        iMqPushService.updateStudentGradeLast(studentGrade.getYearPart(), studentGrade.getQuarterNum(), studentGrade.getStudentId(), studentGrade.getSubjectsId(),grade.getLessonType());

        //添加缺课数据
        //iLackCourseLogService.batchAdd(yearPart, quarterNum, schoolId, studentId, subjectsId, yearClassId, gradeId, 1);
        iMqPushService.lackCourseLogBatchAdd(studentGrade.getYearPart(), studentGrade.getQuarterNum(), studentGrade.getSchoolId(), studentGrade.getStudentId(), studentGrade.getSubjectsId(), grade.getYearClassId().getKey(), grade.getId(), 1);
        //添加学生课次
        //iStudentLessonNumService.addStudentLesson(gradeId, studentId);
        iMqPushService.addStudentLesson(grade.getId(), studentGrade.getStudentId());
        //添加智能课帐号
        /*if (subjectsId.equals(1L)){
            iStudentAccountService.applyAddStudentAccount(schoolId, studentId, gradeId, courseId);
        }*/
        //同步帐号信息到其它系统
        iMqPushService.updateStudentAccount(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getStudentId(), grade.getSubjectsId());
    }

    @Override
    public List<Grade> getStudentGradeTime(Integer yearPart,
                                           Integer quarterNum,
                                           Long schoolId,
                                           Long studentId,
                                           String lessonType,
                                           String unSubjectsId,
                                           String weekDates,
                                           String schedulingType
    ){
        return studentGradeMapper.getStudentGradeTime(yearPart,quarterNum,schoolId,studentId,lessonType,unSubjectsId,weekDates,schedulingType);
    }

    /**
     * 根据精品课给智能课或者刷题班分班
     * @param studentGrade
     */
    @Override
    public void autoAllotStudentGrade(StudentGrade studentGrade){
       Integer isVacation = iDictService.getIsVacation(studentGrade.getQuarterNum());
       if (isVacation == 1){
           //假期班
           //寒假班
           if (studentGrade.getQuarterNum().equals(1)){
               this.winterVacation(studentGrade);
           }else {
               //暑假班，还不确定自动分班方式，确定后再开发
                this.summerVacation(studentGrade);
           }
       }else {
           //学期班
           this.semester(studentGrade);
       }
    }

    //学期班（春季班）
    public  void semester(StudentGrade studentGrade){

        //精品课排课
        Grade grade = iGradeService.getById(studentGrade.getGradeId());

        Integer yearPart = studentGrade.getYearPart();
        Integer quarterNum = studentGrade.getQuarterNum();
        Integer yearClassId = studentGrade.getYearClassId();
        Long subjectsId = studentGrade.getSubjectsId();
        Long studentId = studentGrade.getStudentId();
        Long schoolId = studentGrade.getSchoolId();
        Integer lessonType;
        if (subjectsId.equals(1L)){
            lessonType = 2;
        }else {
            lessonType =3;
        }

        Integer weekType = 1;

        //已排的智能课或者刷题班
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part",studentGrade.getYearPart());
        studentGradeQueryWrapper.eq("quarter_num",studentGrade.getQuarterNum());
        studentGradeQueryWrapper.eq("student_id",studentGrade.getStudentId());
        studentGradeQueryWrapper.eq("subjects_id",studentGrade.getSubjectsId());
        studentGradeQueryWrapper.eq("lesson_type",lessonType);
        studentGradeQueryWrapper.in("reading_status",0,1);
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
        List<SchoolDateTime> schoolDateTimeList = new ArrayList<>();

        for (StudentGrade studentGradeInfo:studentGradeList){
            Grade gradeInfo = iGradeService.getById(studentGradeInfo.getGradeId());
            SchoolDateTime  schoolDateTime = new SchoolDateTime();
            schoolDateTime.setTimeStart(gradeInfo.getTimeStart());
            schoolDateTime.setTimeEnd(gradeInfo.getTimeEnd());
            schoolDateTimeList.add(schoolDateTime);

            //是否与已排精品课时间冲突
            List<StudentGrade> studentGradeListClash = studentGradeMapper.getStudentGradeClash(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getStudentId(),1,schoolDateTimeList,grade.getWeekDates(),null);
            if (studentGradeListClash.size()>0){
                //与精品课冲突
                //冲突删除，删除自动排课的，手动排的不删除,因为这里值为2是自动排的
                if (studentGradeInfo.getAddType().equals(2)){
                    this.removeById(studentGradeInfo);
                }
            }
        }


        //查看已排了几次
        Integer yetCount = 0;
        yetCount = studentGradeMapper.getYetCount(yearPart,quarterNum,subjectsId,studentId,lessonType);
        Integer shouldCount = 0;
        if (subjectsId.equals(1L)){
            shouldCount = 2 - yetCount;
        }else {
            shouldCount = 1 - yetCount;
        }

        //先排周内
        shouldCount = this.weekDayInside(studentGrade,shouldCount);


//        Integer isBoutique = 0;
//        //精品课是否在周末
//        if (grade.getWeekDates().equals("6") || grade.getWeekDates().equals("0")){
//            isBoutique = 1;
//        }

        //还有需要排班，再排周末
        if (shouldCount>0){
            if (grade.getWeekDates().equals("6") || grade.getWeekDates().equals("0")){
                //周末与精品课同一天
                shouldCount = this.semesterWeekend(studentGrade,grade,shouldCount);
                if (shouldCount>0){
                    String wekkDates = grade.getWeekDates().equals("6") ? "0" : "6";
                    //周末与精品课同一天，还需要再排
                    shouldCount = this.semesterWeekend(studentGrade,grade,shouldCount,wekkDates);
                }
            }else {
                //周末与精品课不同一天
                String[] weekDatesArr = {"6","0"};
                for (String weekDates : weekDatesArr){
                    if (shouldCount<=0){
                        continue;
                    }
                    shouldCount = this.semesterWeekend(studentGrade,grade,shouldCount,weekDates);
                }
            }
        }

    }

    /**
     * 周内
     * @param studentGrade
     */
    public Integer weekDayInside(StudentGrade studentGrade,Integer shouldCount){

        Integer yearPart = studentGrade.getYearPart();
        Integer quarterNum = studentGrade.getQuarterNum();
        Integer yearClassId = studentGrade.getYearClassId();
        Long subjectsId = studentGrade.getSubjectsId();
        Long studentId = studentGrade.getStudentId();
        Long schoolId = studentGrade.getSchoolId();
        Integer lessonType;
        if (subjectsId.equals(1L)){
            lessonType = 2;
        }else {
            lessonType =3;
        }
        Integer weekType = 1;

        //获取对应年级周内可排时间表
        List<GradeAutoSet> gradeAutoSetList = iGradeAutoSetService.getAutoTime(yearPart,quarterNum,weekType,lessonType,yearClassId);

        String weekDates;
        //周内
        for (GradeAutoSet gradeAutoSet:gradeAutoSetList){
            if (shouldCount <=0){
                continue;
            }
            //小学
            if (yearClassId <= 6){
                weekDates = "2,3,4";
            }else {
                //初中
                weekDates = "5";
            }
            List<Grade> gradeList = gradeMapper.getSchdulingGrade(yearPart,quarterNum,schoolId,subjectsId,yearClassId,lessonType,studentId,weekDates,gradeAutoSet.getTimeStart(),gradeAutoSet.getTimeEnd(),weekType);
            if (gradeList.size()>0){
                for (Grade grade:gradeList){
                    if (shouldCount <=0){
                        continue;
                    }
                    this.addDataToStudentGrade(grade,studentId);
                    shouldCount--;
                }
            }
        }

        return shouldCount;
    }

    /**
     * 周末与精品课同一天
     * @param studentGrade
     */
    public Integer  semesterWeekend(StudentGrade studentGrade,Grade grade,Integer shouldCount){

        if (grade.getLessonType().equals(1) && grade.getIsAutoScheduling().equals(1)){
            Integer lessonType = 2;
            if (!grade.getSubjectsId().equals(1L)){
                lessonType = 3;
            }

            //已排的智能课或者刷题班
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part",studentGrade.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num",studentGrade.getQuarterNum());
            studentGradeQueryWrapper.eq("student_id",studentGrade.getStudentId());
            studentGradeQueryWrapper.eq("subjects_id",studentGrade.getSubjectsId());
            studentGradeQueryWrapper.eq("lesson_type",lessonType);
            studentGradeQueryWrapper.in("reading_status",0,1);
            List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
            List<SchoolDateTime> schoolDateTimeList = new ArrayList<>();

            for (StudentGrade studentGradeInfo:studentGradeList){
                Grade gradeInfo = iGradeService.getById(studentGradeInfo.getGradeId());
                SchoolDateTime  schoolDateTime = new SchoolDateTime();
                schoolDateTime.setTimeStart(gradeInfo.getTimeStart());
                schoolDateTime.setTimeEnd(gradeInfo.getTimeEnd());
                schoolDateTimeList.add(schoolDateTime);

                //是否与已排课时间冲突
                List<StudentGrade> studentGradeListClash = studentGradeMapper.getStudentGradeClash(studentGrade.getYearPart(),studentGrade.getQuarterNum(),grade.getSchoolId(),studentGrade.getStudentId(),1,schoolDateTimeList,grade.getWeekDates(),null);
                if (studentGradeListClash.size()>0){
                    //与精品课冲突
                    // 冲突删除，删除自动排课的，手动排的不删除,因为这里值为2是自动排的
                    if (studentGradeInfo.getAddType().equals(2)){
                        this.removeById(studentGradeInfo);
                    }
                    shouldCount++;//删除后，应添加排课加1
                }else {
                }
            }

            //获取已排课时间（包含精品课，智能课，刷题班）
            List<Grade> gradeList = studentGradeMapper.getStudentGradeTime(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getStudentId(),null,null,grade.getWeekDates(),null);

            //已排课的时间
            schoolDateTimeList = new ArrayList<>();
            for (Grade gradeInfo:gradeList){
                SchoolDateTime  schoolDateTime = new SchoolDateTime();
                schoolDateTime.setTimeStart(gradeInfo.getTimeStart());
                schoolDateTime.setTimeEnd(gradeInfo.getTimeEnd());
                schoolDateTimeList.add(schoolDateTime);
            }
            if (shouldCount >0){
                //不存在排课，需要添加排课
                //获取可排时间
                //List<Grade> grades = studentGradeMapper.getGradeUnClash(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList);
                Grade yetGrade = this.getAllotGrade(grade,schoolDateTimeList,lessonType,studentGrade.getStudentId(),grade.getWeekDates());
                if (yetGrade != null){
                    StudentGrade studentGradeAi = new StudentGrade();
                    BeanUtils.copyProperties(studentGrade,studentGradeAi);
                    studentGradeAi.setId(null);
                    studentGradeAi.setOrderDetailId(null);
                    studentGradeAi.setLessonType(lessonType);
                    studentGradeAi.setGradeId(yetGrade.getId());
                    studentGradeAi.setCourseId(yetGrade.getCourseId());
                    studentGradeAi.setRemark("");
                    studentGradeAi.setUseCourseCount(0);
                    studentGradeAi.setAddType(2);//自动分班

                    QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                    orderDetailQueryWrapper.eq("school_id", studentGrade.getSchoolId());
                    orderDetailQueryWrapper.eq("year_part", yetGrade.getYearPart());
                    orderDetailQueryWrapper.eq("quarter_num", yetGrade.getQuarterNum());
                    orderDetailQueryWrapper.eq("subjects_id", studentGrade.getSubjectsId());
                    orderDetailQueryWrapper.eq("student_id", studentGrade.getStudentId());
                    orderDetailQueryWrapper.eq("lesson_type", lessonType);
                    orderDetailQueryWrapper.ne("status", 2);
                    orderDetailQueryWrapper.orderByDesc("created_at");
                    orderDetailQueryWrapper.last("limit 1");
                    OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
                    if (orderDetail != null) {
                        studentGradeAi.setOrderDetailId(orderDetail.getId());
                        //studentGradeAi.setReadingStatus(ReadingStatusEnum.IN_READING);//由预分班改为在读
                    }
                    this.save(studentGradeAi);
                    studentGradeAi.setCreatedAt(LocalDateTime.now().withNano(0));
                    this.updateById(studentGradeAi);
                    shouldCount--;
                }
            }
        }
        return shouldCount;
    }

    /**
     * 周末与精品课在不同一天
     * @param studentGrade
     */
    public Integer semesterWeekend(StudentGrade studentGrade,Grade grade,Integer shouldCount,String weekDates){

        Integer yearPart = studentGrade.getYearPart();
        Integer quarterNum = studentGrade.getQuarterNum();
        Integer yearClassId = studentGrade.getYearClassId();
        Long subjectsId = studentGrade.getSubjectsId();
        Long studentId = studentGrade.getStudentId();
        Long schoolId = studentGrade.getSchoolId();
        Integer lessonType;
        if (subjectsId.equals(1L)){
            lessonType = 2;
        }else {
            lessonType =3;
        }
        Integer weekType = 2;//周末
        String orderType = "asc";//正序
        //获取已排课时间（包含精品课，智能课，刷题班）
        List<Grade> gradeList = studentGradeMapper.getStudentGradeTime(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getStudentId(),null,null,grade.getWeekDates(),null);
        //已排课的时间
        List<SchoolDateTime> schoolDateTimeList = new ArrayList<>();
        for (Grade gradeInfo:gradeList){
            SchoolDateTime  schoolDateTime = new SchoolDateTime();
            schoolDateTime.setTimeStart(gradeInfo.getTimeStart());
            schoolDateTime.setTimeEnd(gradeInfo.getTimeEnd());
            schoolDateTimeList.add(schoolDateTime);
        }

        //获取对应年级周内可排时间表
        List<GradeAutoSet> gradeAutoSetList = iGradeAutoSetService.getAutoTime(yearPart,quarterNum,weekType,lessonType,yearClassId);
        for (GradeAutoSet gradeAutoSet:gradeAutoSetList){
            if (shouldCount <=0){
                continue;
            }
            Grade mayGrade = studentGradeMapper.getGradeUnClashWeekEnd(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,orderType,studentId,weekDates,gradeAutoSet.getTimeStart(),gradeAutoSet.getTimeEnd());
            if (!Objects.isNull(mayGrade)){
                this.addDataToStudentGrade(mayGrade,studentId);
                shouldCount--;
            }
        }
        return shouldCount;
    }



    //寒假班排课
    public void  winterVacation(StudentGrade studentGrade){
        //精品课排课
        Grade grade = iGradeService.getById(studentGrade.getGradeId());

        if (grade.getLessonType().equals(1) && grade.getIsAutoScheduling().equals(1)){
            Integer lessonType = 2;
            if (!grade.getSubjectsId().equals(1L)){
                lessonType = 3;
            }

            //已排的智能课或者刷题班
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part",studentGrade.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num",studentGrade.getQuarterNum());
            studentGradeQueryWrapper.eq("student_id",studentGrade.getStudentId());
            studentGradeQueryWrapper.eq("subjects_id",studentGrade.getSubjectsId());
            studentGradeQueryWrapper.eq("lesson_type",lessonType);
            studentGradeQueryWrapper.in("reading_status",0,1);
            List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
            List<SchoolDateTime> schoolDateTimeList = new ArrayList<>();

            List<StudentGrade> studentGradeListUnClash = new ArrayList<>();
            for (StudentGrade studentGradeInfo:studentGradeList){
                Grade gradeInfo = iGradeService.getById(studentGradeInfo.getGradeId());
                SchoolDateTime  schoolDateTime = new SchoolDateTime();
                schoolDateTime.setTimeStart(gradeInfo.getTimeStart());
                schoolDateTime.setTimeEnd(gradeInfo.getTimeEnd());
                schoolDateTimeList.add(schoolDateTime);

                //是否与已排课时间冲突
                List<StudentGrade> studentGradeListClash = studentGradeMapper.getStudentGradeClash(studentGrade.getYearPart(),studentGrade.getQuarterNum(),grade.getSchoolId(),studentGrade.getStudentId(),1,schoolDateTimeList,null,null);
                if (studentGradeListClash.size()>0){
                    //与精品课冲突
                    //冲突删除，删除自动排课的，手动排的不删除,因为这里值为2是自动排的
                    if (studentGradeInfo.getAddType().equals(2)){
                        this.removeById(studentGradeInfo);
                    }
                }else {
                    //不冲突
                    studentGradeListUnClash.add(studentGradeInfo);
                }
            }

            //获取已排课时间
            List<Grade> gradeList = studentGradeMapper.getStudentGradeTime(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getStudentId(),null,null,null,null);

            //已排课的时间
            schoolDateTimeList = new ArrayList<>();
            for (Grade gradeInfo:gradeList){
                SchoolDateTime  schoolDateTime = new SchoolDateTime();
                schoolDateTime.setTimeStart(gradeInfo.getTimeStart());
                schoolDateTime.setTimeEnd(gradeInfo.getTimeEnd());
                schoolDateTimeList.add(schoolDateTime);
            }

            if (studentGradeListUnClash.size() == 0){
                //不存在排课，需要添加排课
                //获取可排时间
                //List<Grade> grades = studentGradeMapper.getGradeUnClash(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList);
                Grade yetGrade = this.getAllotGrade(grade,schoolDateTimeList,lessonType,studentGrade.getStudentId(),null);
                if (yetGrade != null){
                    //因为假期班一天只排一个班，所以先删除再添加
                    QueryWrapper<StudentGrade> delWrapper = new QueryWrapper<>();
                    delWrapper.eq("year_part",yetGrade.getYearPart());
                    delWrapper.eq("quarter_num",yetGrade.getYearPart());
                    delWrapper.eq("lesson_type",lessonType);
                    delWrapper.eq("student_id",studentGrade.getStudentId());
                    delWrapper.eq("subjects_id",studentGrade.getSubjectsId());
                    this.remove(delWrapper);

                    StudentGrade studentGradeAi = new StudentGrade();
                    BeanUtils.copyProperties(studentGrade,studentGradeAi);
                    studentGradeAi.setId(null);
                    studentGradeAi.setOrderDetailId(null);
                    studentGradeAi.setLessonType(lessonType);
                    studentGradeAi.setGradeId(yetGrade.getId());
                    studentGradeAi.setCourseId(yetGrade.getCourseId());
                    studentGradeAi.setRemark("");
                    studentGradeAi.setUseCourseCount(0);

                    QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                    orderDetailQueryWrapper.eq("school_id", studentGrade.getSchoolId());
                    orderDetailQueryWrapper.eq("year_part", yetGrade.getYearPart());
                    orderDetailQueryWrapper.eq("quarter_num", yetGrade.getQuarterNum());
                    orderDetailQueryWrapper.eq("subjects_id", studentGrade.getSubjectsId());
                    orderDetailQueryWrapper.eq("student_id", studentGrade.getStudentId());
                    orderDetailQueryWrapper.eq("lesson_type", lessonType);
                    orderDetailQueryWrapper.ne("status", 2);
                    orderDetailQueryWrapper.orderByDesc("created_at");
                    orderDetailQueryWrapper.last("limit 1");
                    OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
                    if (orderDetail != null) {
                        studentGradeAi.setOrderDetailId(orderDetail.getId());
                        //studentGradeAi.setReadingStatus(ReadingStatusEnum.IN_READING);//由预分班改为在读
                    }
                    this.save(studentGradeAi);
                    studentGradeAi.setCreatedAt(LocalDateTime.now().withNano(0));
                    this.updateById(studentGradeAi);

                }
            }
        }
    }


    /**
     * 暑假智能课与刷题班排班
     * @param studentGrade
     */
    public void summerVacation(StudentGrade studentGrade){
        //精品课排课
        Grade grade = iGradeService.getById(studentGrade.getGradeId());
        if (grade.getLessonType().equals(1) && grade.getIsAutoScheduling().equals(1)){
            Integer lessonType = 2;
            if (!grade.getSubjectsId().equals(1L)){
                lessonType = 3;
            }
            if (grade.getIsScheduling().equals(1)){
                String timeStart = grade.getTimeStart();
                String timeEnd = grade.getTimeEnd();

                String schedulingType = grade.getSchedulingType();
                String schedulingTypeAdd = "";
                if (StringUtils.isNotBlank(schedulingType)){
                    if (schedulingType.equals("1")){
                        if (schedulingType.equals("A天")){
                            schedulingTypeAdd = "B天";
                        }else if (schedulingType.equals("B天")){
                            schedulingTypeAdd = "A天";
                        }
                    }
                    if (StringUtils.isNotBlank(schedulingTypeAdd)){
                        //获取已排班时间

                        //已排的智能课或者刷题班
                        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                        studentGradeQueryWrapper.eq("year_part",studentGrade.getYearPart());
                        studentGradeQueryWrapper.eq("quarter_num",studentGrade.getQuarterNum());
                        studentGradeQueryWrapper.eq("student_id",studentGrade.getStudentId());
                        studentGradeQueryWrapper.eq("subjects_id",studentGrade.getSubjectsId());
                        studentGradeQueryWrapper.eq("lesson_type",lessonType);
                        studentGradeQueryWrapper.in("reading_status",0,1);
                        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
                        List<SchoolDateTime> schoolDateTimeList = new ArrayList<>();

                        List<StudentGrade> studentGradeListUnClash = new ArrayList<>();
                        for (StudentGrade studentGradeInfo:studentGradeList){
                            Grade gradeInfo = iGradeService.getById(studentGradeInfo.getGradeId());
                            String schedulingTypeStr = gradeInfo.getSchedulingType();

                            SchoolDateTime  schoolDateTime = new SchoolDateTime();
                            schoolDateTime.setTimeStart(gradeInfo.getTimeStart());
                            schoolDateTime.setTimeEnd(gradeInfo.getTimeEnd());
                            schoolDateTimeList.add(schoolDateTime);

                            //是否与已排课时间冲突
                            List<StudentGrade> studentGradeListClash = studentGradeMapper.getStudentGradeClash(studentGrade.getYearPart(),studentGrade.getQuarterNum(),grade.getSchoolId(),studentGrade.getStudentId(),1,schoolDateTimeList,null,schedulingTypeStr);
                            if (studentGradeListClash.size()>0){
                                //与精品课冲突
                                //冲突删除，删除自动排课的，手动排的不删除,因为这里值为2是自动排的
                                if (studentGradeInfo.getAddType().equals(2)){
                                    this.removeById(studentGradeInfo);
                                }
                            }else {
                                //不冲突
                                studentGradeListUnClash.add(studentGradeInfo);
                            }
                        }

                        //获取已排课时间
                        List<Grade> gradeList = studentGradeMapper.getStudentGradeTime(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getStudentId(),null,null,null,schedulingType);

                        //已排课的时间
                        schoolDateTimeList = new ArrayList<>();
                        for (Grade gradeInfo:gradeList){
                            SchoolDateTime  schoolDateTime = new SchoolDateTime();
                            schoolDateTime.setTimeStart(gradeInfo.getTimeStart());
                            schoolDateTime.setTimeEnd(gradeInfo.getTimeEnd());
                            schoolDateTimeList.add(schoolDateTime);
                        }

                        if (studentGradeListUnClash.size() == 0){
                            //不存在排课，需要添加排课
                            //获取可排时间
                            //List<Grade> grades = studentGradeMapper.getGradeUnClash(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList);
                            Grade yetGrade = this.getAllotGradeForSummerVacation(grade,schoolDateTimeList,lessonType,studentGrade.getStudentId(),schedulingType);
                            if (!Objects.isNull(yetGrade)){
                                //因为假期班一天只排一个班，所以先删除再添加
                                QueryWrapper<StudentGrade> delWrapper = new QueryWrapper<>();
                                delWrapper.eq("year_part",yetGrade.getYearPart());
                                delWrapper.eq("quarter_num",yetGrade.getYearPart());
                                delWrapper.eq("lesson_type",lessonType);
                                delWrapper.eq("student_id",studentGrade.getStudentId());
                                delWrapper.eq("subjects_id",studentGrade.getSubjectsId());
                                this.remove(delWrapper);

                                StudentGrade studentGradeAi = new StudentGrade();
                                BeanUtils.copyProperties(studentGrade,studentGradeAi);
                                studentGradeAi.setId(null);
                                studentGradeAi.setOrderDetailId(null);
                                studentGradeAi.setLessonType(lessonType);
                                studentGradeAi.setGradeId(yetGrade.getId());
                                studentGradeAi.setCourseId(yetGrade.getCourseId());
                                studentGradeAi.setRemark("");
                                studentGradeAi.setUseCourseCount(0);

                                QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                                orderDetailQueryWrapper.eq("school_id", studentGrade.getSchoolId());
                                orderDetailQueryWrapper.eq("year_part", yetGrade.getYearPart());
                                orderDetailQueryWrapper.eq("quarter_num", yetGrade.getQuarterNum());
                                orderDetailQueryWrapper.eq("subjects_id", studentGrade.getSubjectsId());
                                orderDetailQueryWrapper.eq("student_id", studentGrade.getStudentId());
                                orderDetailQueryWrapper.eq("lesson_type", lessonType);
                                orderDetailQueryWrapper.ne("status", 2);
                                orderDetailQueryWrapper.orderByDesc("created_at");
                                orderDetailQueryWrapper.last("limit 1");
                                OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
                                if (orderDetail != null) {
                                    studentGradeAi.setOrderDetailId(orderDetail.getId());
                                    //studentGradeAi.setReadingStatus(ReadingStatusEnum.IN_READING);//由预分班改为在读
                                }
                                this.save(studentGradeAi);
                                studentGradeAi.setCreatedAt(LocalDateTime.now().withNano(0));
                                this.updateById(studentGradeAi);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     *
     * @param grade
     * @param studentId
     */
    public void addDataToStudentGrade(Grade grade,Long studentId){
        StudentGrade studentGradeAi = new StudentGrade();
        studentGradeAi.setStudentId(studentId);
        studentGradeAi.setSchoolId(grade.getSchoolId());
        studentGradeAi.setYearPart(grade.getYearPart());
        studentGradeAi.setQuarterNum(grade.getQuarterNum());
        studentGradeAi.setGradeId(grade.getId());
        studentGradeAi.setCourseId(grade.getCourseId());
        studentGradeAi.setLessonType(grade.getLessonType());
        studentGradeAi.setSubjectsId(grade.getSubjectsId());
        studentGradeAi.setYearClassId(grade.getYearClassId().getKey());
        studentGradeAi.setAddType(2);

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("school_id", grade.getSchoolId());
        orderDetailQueryWrapper.eq("year_part", grade.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", grade.getQuarterNum());
        orderDetailQueryWrapper.eq("subjects_id", grade.getSubjectsId());
        orderDetailQueryWrapper.eq("student_id", studentId);
        orderDetailQueryWrapper.eq("lesson_type", grade.getLessonType());
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.orderByDesc("created_at");
        orderDetailQueryWrapper.last("limit 1");
        OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
        if (orderDetail != null) {
            studentGradeAi.setOrderDetailId(orderDetail.getId());
        }

        this.save(studentGradeAi);
        //studentGradeAi.setCreatedAt(LocalDateTime.now().withNano(0));
        //this.updateById(studentGradeAi);
    }



    /**
     *
     * @param grade 精品课班级
     * @return
     */
    public Grade getAllotGrade(Grade grade,List<SchoolDateTime> schoolDateTimeList,Integer lessonType,Long studentId,String  weekDates){
        LocalTime startTime = LocalTime.parse(grade.getTimeStart());
        // 获取当前日期的中午12点时间
        LocalTime noonTime = LocalTime.NOON;
        LocalTime nightTime = LocalTime.parse("18:00:00");//晚上时间点
        // 如果需要获取包含日期的中午12点时间
        LocalDateTime noonDateTime = LocalDateTime.of(LocalDateTime.now().toLocalDate(), noonTime);
        Integer noonType =1;//上午，2下午,3晚上
        if (startTime.isAfter(noonTime)){
            noonType = 2;
        }else if (startTime.isAfter(nightTime)){
            noonType = 3;
        }

        Integer diffType = 2;//智能课或者刷题班上课时间 1小于精品课时间，2大于精品课时间
        Integer diffNoonType = noonType;
        String orderType = "asc";//正序
        Grade mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
        if (noonType.equals(1)){
            if (mayGrade == null){
                diffType = 1;
                orderType = "desc";
                //上午小于上课时间
                mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
                if (mayGrade == null){
                    diffNoonType = 2;//下午
                    diffType = 2;
                    orderType = "asc";
                    //下午大于上课时间
                    mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
                }
                if (mayGrade == null){
                    diffNoonType = 3;//晚上
                    diffType = 2;
                    orderType = "asc";
                    //晚上大于上课时间
                    mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
                }

            }
        }else if (noonType.equals(2)){
            if (mayGrade == null){
                diffType = 1;
                orderType = "desc";
                //下午小于上课时间
                mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
                if (mayGrade == null){
                    diffNoonType = 3;//晚上
                    diffType = 2;
                    orderType = "asc";
                    //晚上大于上课时间
                    mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
                }
                if (mayGrade == null){
                    diffNoonType = 1;//早上
                    diffType = 1;
                    orderType = "desc";
                    mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
                }
            }
        }else if (noonType.equals(3)){
            diffType = 1;
            orderType = "desc";
            //晚上小于上课时间
            mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
            if (mayGrade == null){
                diffNoonType = 2;//下午
                diffType = 1;
                orderType = "desc";
                //下午小于上课时间
                mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
            }
            if (mayGrade == null){
                diffNoonType = 1;
                diffType = 1;
                orderType = "desc";
                //早上小于上课时间
                mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,weekDates,null);
            }
        }
        return mayGrade;
    }

    public Grade getAllotGradeForSummerVacation(Grade grade,List<SchoolDateTime> schoolDateTimeList,Integer lessonType,Long studentId,String  schedulingType){
        Integer noonType = 0;//0所有，1上午，2下午,3晚上
        Integer diffType = 2;//智能课或者刷题班上课时间 1小于精品课时间，2大于精品课时间
        Integer diffNoonType = noonType;
        String orderType = "asc";//正序
        Grade mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,null,schedulingType);
        if (!Objects.isNull(mayGrade)){
            diffType = 1;
            orderType = "desc";
            mayGrade = studentGradeMapper.getGradeUnClash(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId(),lessonType,schoolDateTimeList,diffNoonType,diffType,grade.getTimeStart(),orderType,studentId,null,schedulingType);
        }
        return mayGrade;
    }
}
